/**
 * Created by ZFL on 2017/12/26.
 */

/** 全局插件 **/
$.extend({
    ajaxApi:function(){
        return "http://api.biz.nongtebest.com/";

    },
    wxApi:function () {
        return "http://h5bj.nongtebest.com";

    },
    //appApi:function () {
    //    return "http://h5.shopxiaoming.com/";
    //
    //
    //},
    imgApi:function () {
        return "";
        //return "";//正式站
    },
    /*2016-07-09  获取url参数值 */
    getPara:function(name,url){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        if (url) {
            if (url.indexOf("?") != -1)
                url = url.split("?")[1];
        } else if (window.location.search.length > 1) {
            url = decodeURI(window.location.search.substr(1));
        } else {
            return '';
        }
        var r = url.match(reg);
        if (r != null) return unescape(r[2]); return '';
    },
    getUrl:function(name,url){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        if (url) {
            if (url.indexOf("?") != -1)
                url = url.split("?")[1];
        } else if (window.location.search.length > 1) {
            url = decodeURI(window.location.search.substr(1));
        } else {
            return '';
        }
        var r='';
        if(url.indexOf(name)>-1){
            var $index=url.indexOf(name)+name.length+1;
            r = url.substr($index);
        }
        return r;
    },
    GetRequest:function(){
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for(var i = 0; i < strs.length; i ++) {
                theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    },
    /*2016-07-09 ajax请求*/
    ajaxHandler:function(ajaxObj){
        var visible = ajaxObj.visible || "show";
        var approve = ajaxObj.approve || false;
        var g={
            loading:function (text) {
                var _content = "";
                if(text) _content =text;
                if(visible=="show"){ //显示加载 loading
                    var loader = '<div class="loading-box"><div class="loading-bounce-box"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div><div class="loading-content">'+_content+'</div></div>';
                    if($(".loading-box").length<1){
                        $("body").append(loader);
                        $(".loading-box").addClass("open");
                    }else{
                        if(!$(".loading-box").hasClass("open")){
                            $(".loading-box").addClass("open");
                        }
                    }
                }
            },
            //隐藏进度条
            hideload:function () {
                if($(".loading-box").length>0){
                    var visibleTime =ajaxObj.visibleTime || 0; //毫秒
                    if(visibleTime>0){
                        setTimeout(function () {
                            $(".loading-box").removeClass("open");
                        },visibleTime)
                    }else{
                        $(".loading-box").removeClass("open");
                    }
                }
            },
            // 成功返回处理
            success:function (data, textStatus) {
                try {
                    if (data == undefined || data == '') {
                        g.hideload();
                        return;
                    }
                    var result;
                    if(data.code){
                        result=data;
                    }else{
                        result = JSON.parse(data);
                    }
                    if (ajaxObj.success){
                        ajaxObj.success(result,textStatus);
                    }
                    g.hideload();
                } catch (e) {
                    //g.toast("系统繁忙，请稍后再试！");
                    console.log(e.name + ": " + e.message);
                    setTimeout(function () {
                        g.hideload();
                    }, 2000);
                }
            },
            beforeSend:function (XMLHttpRequest) {
                if(approve){
                    //XMLHttpRequest.setRequestHeader("userToken","da5d1be1-cd10-4eb2-bfe9-70ccc98c8410");
                    if($.getStorage("xm_uData")){
                        XMLHttpRequest.setRequestHeader("userToken",'h5:'+JSON.parse($.getStorage("xm_uData")).token);
                    }else{
                        if($.getPara("appToken")){
                            XMLHttpRequest.setRequestHeader("userToken",'h5:'+$.getPara("appToken"));
                        }else if($.getStorage("appToken")){
                            XMLHttpRequest.setRequestHeader("userToken",'h5:'+$.getStorage("appToken"));
                        }
                    }
                }
            },
            // 失败返回处理
            error:function (e) {
                $.errorVue(); //显示异常
                $.delStorage("hx_wx");
                $.delStorage("xm_uData");
                $.delStorage("hx_AccessTokenIndex");
                $.delStorage("wx");
                $.delStorage("uData");
                $.delStorage("AccessTokenIndex");
                g.hideload();

                console.error(e);
            },
            // 提交动作
            submit:function () {
                var param = null;
                if (ajaxObj.model) {
                    if (typeof ajaxObj.model == "function") {
                        param = JSON.stringify(ajaxObj.model());
                    }else{
                        param ="{}";
                    }
                }else{
                    param ="{}";
                }
                var async =ajaxObj.async || "";
                var post = ajaxObj.type || "post";
                var dataType = ajaxObj.dataType || "json";
                var url;
                if(ajaxObj.apiUrl){
                    url = ""+ajaxObj.apiUrl+""+ajaxObj.api+"";
                }else{
                    url = $.ajaxApi()+""+ajaxObj.api+"";
                }
                var option = {
                    type:post,
                    async: true,
                    contentType: "application/json;charset=utf-8",
                    dataType: dataType,
                    url: url,
                    data:''+param+'',
                    beforeSend:g.beforeSend,
                    complete:g.hideload,
                    success: g.success,
                    error: g.error
                };
                var _ajax = $.ajax(option);
                return _ajax;
            }
        };
        //执行
        g.loading();
        return g.submit();
    },
    errorVue:function (text) {
        var $text = (text)?text:'异常，网络请求失败~';
        var html ='<div class="system-error"></div> <div class="system-error-box"> <img class="img" src="../src/images/system_error.png"> <div class="text">'+$text+'</div> </div>';
        $('body').append(html);
    },
    /*显示加载 */
    showScrollLoad:function(){
        var loader = '<div class="loading-box-bottom"> <div class="loading-bounce-box"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div></div>';
        if($(".loading-box-bottom").length<1){
            $("body").append(loader);
            $(".loading-box-bottom").addClass("open");
        }else{
            if(!$(".loading-box-bottom").hasClass("open")){
                $(".loading-box-bottom").addClass("open");
            }
        }
    },
    /*掩藏加载 */
    hideScrollLoad:function(time){
        if($(".loading-box-bottom").length>0){
            if(time){
                setTimeout(function () {
                    $(".loading-box-bottom").removeClass("open");
                },visibleTime);
            }else{
                $(".loading-box-bottom").removeClass("open");
            }
        }
    },
    /*存储值localstorage */
    setStorage:function (name,value){
        if(window.localStorage.getItem(name)){
            window.localStorage.setItem(name,JSON.stringify(value));
        }else{
            window.localStorage[name] =JSON.stringify(value);
        }
    },
    /*读取localstorage */
    getStorage:function (name){
        if(window.localStorage.getItem(name)){
            return window.localStorage.getItem(name);}
        else {
            return null;
        }
    },
    /* 删除localstorage */
    delStorage:function (name) {
        if(window.localStorage.getItem(name))
            return window.localStorage.removeItem(name);
    },
    //设置cookie
    setCookie:function(name,value){
        var days = 1;
        var exp = new Date();
        exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString()+";path=/";
    },
    //读取cookie
    getCookie:function(name){
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg)){
            return unescape(arr[2]);
        }else{
            return null;
        }
    },
    //删除cookie
    delCookie:function(name){
        var exp = new Date();
        exp.setTime(exp.getTime() + (-1 * 24 * 60 * 60 * 1000));
        var cval =$.getCookie(name);
        document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
    },
    //关闭悬浮的导航栏
    closeFixed:function(){
        $('.fixed-tab').hide();
    },
    //跳转到下载链接
    downloadApp:function(){
       window.location.href=''
    },
    /*是否是微信浏览器 */
    isWX:function(){
        var ua = navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i)=="micromessenger") {
            return true;
        } else {
            return false;
        }
    },
    /*penghe 2016-07-09 微信获取Code*/
    GetWXCode:function(UrlHosts){
        $.delStorage("hx_wx");
        $.delStorage("hx_AccessTokenIndex");
        $.delStorage("wx");
        $.delStorage("uData");
        $.delStorage("AccessTokenIndex");
        var urlhost = $.wxApi()+'b2c/user/getOpenid.html';


        var wxUrl="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9b33309adb6d5699&redirect_uri="+encodeURIComponent(urlhost)+"&response_type=code&scope=snsapi_base#wechat_redirect";


        window.location.href=wxUrl;
    },




    /* ph 2016-07-09 通过网页授权获取用户基本信息 */
    GetAccessToken:function () {
        $.ajaxHandler({
            model: function () {
                var obj = {};
                obj.code = $.getPara("code");
                obj.type =1;// 0只获取openId，1同时获取用户信息
//
                console.log(obj)
                return obj;
            },
            visibleTime: 0,
            dataType: "json",
            approve: true,
            //apiUrl:$.appApi(),
            api: 'yg_baijiaapp/unDefinedUser/authorization',
            success: function (result) {

                if (result.code == 10000) {
                    var data=result.data;
                    if(data.openId){
                        var obj ={};

                        obj.openid  = data.openId;
                        window.localStorage.setItem("xmOpenid",data.openId);
                        if($.getUrl('href')!=''){
                            var url = $.getUrl('href');
                            if($.getPara("code")){
                                var $index = url.indexOf('&code');
                                url = url.substr(0,$index);
                            }
                            window.location.href  = url;
                        }else{
                            //默认跳转结算
                            //window.location.href  = $.wxApi()+'b2c/pay/goodsPay.html';

                            window.location.href  = $.wxApi()+'b2c/pay/goodsPay.html';
                        }
                    }

                }else {
                    YDUI.dialog.toast(result.message+result.code,'error',1000);
                }
            }
        })




    },
    //更新信息
    updataInfo:function(id){
        var obj={};
        $.ajaxHandler({
            model:function(){
                obj.type=2;
                obj.openId=id;

                return obj;
            },
            visible:"hide",
            visibleTime:0,
            dataType:"json",
            api:"yg_baijiaapp/unDefinedUser/getUserInfoByOpenId",
            success:function (result) {
                //console.log(result);
                if (result.code == 10000) {
                    var data = result.data;
                    var _obj  ={};
                    //console.log(data);
                    _obj.nickName  = data.nickName;
                    if(data.picture.toString().indexOf('http')>-1){
                        _obj.picture  = data.picture;
                    }else if(data.picture!=''){
                        _obj.picture  =data.picture;
                    }else{
                        //默认头像
                        _obj.picture  ='../images/user/user_img.png';
                    }
                    _obj.userName  = data.userName;
                    _obj.userId  = data.userId;
                    _obj.level = data.level;
                    _obj.token = data.token;
                    _obj.persionId=data.persionId;
                    _obj.recommendFrom  =data.recommendFrom;
                    _obj.money  = data.money;
                    _obj.sex  = data.sex;
                    if(data.openId){
                        _obj.openId = data.openId;
                        window.localStorage.setItem("xmOpenid",data.openId);
                    }else{
                        _obj.openId=$.getStorage("xmOpenid")
                    }
                    $.setStorage("xm_uData",_obj);
                    com_obj.userId = data.userId;//用户Id
                    console.log(com_obj.userId)
                    com_obj.roleId = data.roleId;//用户角色Id

                } else {
                    com_obj.userId=0;
                    $.delStorage('xm_uData');

                }
            }

        })
    },
    showLogin:function (UrlHosts) {
        var urlhost = (UrlHosts)?UrlHosts:window.location.href;
        window.location.href = '/b2c/user/user_login.html?href='+urlhost+'';
    },
    homeLogin:function () {
        var urlhost = window.location.href;
        window.location.href = 'user_login.html';
    },
    imgDef:function(){
        var img = event.srcElement;
        img.src = "/b2c/images/default.png";
        img.onerror = null; //控制不要一直跳动
    }
});

/** 对象级别插件 **/
(function($){
    $.fn.extend({
        test:function(content){
            console.log("测试输出内容:"+content);
            //访问     $("a").test();
        }
    });
})(jQuery);

/*public 函数*/
/*保存信息*/
var saveInfo = function(data,text,httpUrl) {
    var _obj  ={};
    //console.log(data);
    _obj.nickName  = data.nickName;
    if(data.picture.toString().indexOf('http')>-1){
        _obj.picture  = data.picture;
    }else if(data.picture!=''){
        _obj.picture  =data.picture;
    }else{
        //默认头像
        _obj.picture  ='../images/user/user_img.png';
    }
    _obj.userName  = data.userName;
    _obj.userId  = data.userId;
    _obj.level = data.level;
    _obj.token = data.token;
    _obj.persionId=data.persionId;
    _obj.recommendFrom  =data.recommendFrom;
    _obj.money  = data.money;
    _obj.sex  = data.sex;
    if(data.openId){
        _obj.openId = data.openId;
        window.localStorage.setItem("xmOpenid",data.openId);
    }else{
        _obj.openId=$.getStorage("xmOpenid")
    }
    $.setStorage('xm_uData',_obj)

    com_obj.userId = data.userId;//用户Id
    console.log(com_obj.userId)
    com_obj.roleId = data.roleId;//用户角色Id
    var urlHttp='';
    YDUI.dialog.toast(text,'success',1000);
    setTimeout(function () {
        if(httpUrl){
            window.location.href =httpUrl;
        }else{
            if ($.getUrl("href") != "") {
                window.location.href = $.getUrl("href");
            } else {
                window.location.href = "/";
            }
        }
    },1500);
    //if($.getStorage("openUrl")){
    //    urlHttp = $.getStorage("openUrl");
    //}
    //
    //if(Number($.getStorage('returnWxpay'))==1){
    //
    //}else if($.getStorage('recommended')&&$.getStorage('recommended')==0){
    //    //正式
    //        window.location.href ='http://h5.hm2019.com/b2c/app/downloadApp.html?status=0';
    //    //测试
    //    //window.location.href ='http://h5.huimei2019.com/b2c/app/downloadApp.html?status=0';
    //
    //}else if(urlHttp!==null&&urlHttp.indexOf('wxPay_success')>-1) {
    //}else  if($.getUrl("href") != "") {
    //    //从登录页面跳转
    //        YDUI.dialog.toast('登录成功','success',1000);
    //       YDUI.dialog.toast(text,1000);
    //        setTimeout(function () {
    //            window.location.href = $.getUrl("href");
    //        }, 1500);
    //
    //}else if(httpUrl){
    //    window.location.href = $.getUrl("href");
    //}else if($.getStorage('openUrl')){
    //    window.location.href =$.getStorage('openUrl');
    //}
    //else{
    //    YDUI.dialog.toast('登录成功','success',1000);
    //    window.location.href ='/index.html';
    //}

    //else{
    //        window.location.href =$.getStorage('openUrl');
    //}



};

/* 减运算，避免数据相除小数点后产生多位数和计算精度损失。*/

function subtractNumber(arg1,arg2){
    return (arg1*1000-arg2*1000)/1000;//防止丢失精度
}
/* 乘运算，避免数据相除小数点后产生多位数和计算精度损失。*/

function SubNumber(arg1,arg2){
    return (arg1*1000)*(arg2*1000)/1000000;//防止丢失精度
}
/*相加运算，避免数据相除小数点后产生多位数和计算精度损失。*/

function andNumber(arg1,arg2){
    return ((arg1*1000)+(arg2*1000))/1000;//防止丢失精度
}
/* 除，避免数据相除小数点后产生多位数和计算精度损失。*/

function divideNumber(arg1,arg2){
    return ((arg1*1000)/(arg2*1000));//防止丢失精度
}
/* 函数：取当前日期(若有参数n，则推后或者提前几天)*/
function getCurrentDay(n, basicDate) {
    var today = basicDate || new Date();
    if (n) {
        today = new Date(today.valueOf() + n * 24 * 60 * 60 * 1000);
    }
    var day = today.getDate();

    var month = today.getMonth() + 1;
    var year = today.getFullYear();
    if (month < 10) {
        var strMonth = "0" + month;
    }
    else {
        strMonth = month;
    }
    if (day < 10) {
        var strDay = "0" + day;
    } else {
        strDay = day;
    }
    var date = year + "-" + strMonth + "-" + strDay;

    return date;
}

/* 函数：取当前月份(若有参数n，则推后或者提前几月) */
function getCurrentMonth(n) {
    var today = new Date();
    if (!n) n = 0;
    var month = today.getMonth() + 1 + n;
    var year = today.getFullYear();
    if (month < 10) {
        var strMonth = "0" + month;
    }
    else {
        strMonth = month;
    }
    var date = year + "-" + strMonth;

    return date;
}

/*函数：获得当前的日期和时间（格式：2009-06-12 12:09:06）*/
function CurentTime() {
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ms = now.getSeconds();     //秒
    var clock = year + "-";

    if (month < 10)
        clock += "0";

    clock += month + "-";

    if (day < 10)
        clock += "0";

    clock += day + " ";

    if (hh < 10) { clock += "0"; }
    clock += hh + ":";
    if (mm < 10) { clock += '0'; }
    clock += mm + ":";
    if (ms < 10) { clock += '0'; }
    clock += ms;
    return (clock);
}

/* 金额格式化函数：s:金额 n:保留几位小数*/
function fmoney(s, n) {
    n = n >= 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    //是否是负数
    var prestr = '';
    if (s.substring(0, 1) == "-") {
        s = s.substring(1, s.length);
        prestr = '-';
    }
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }

    if (n == 0)
        return prestr + t.split("").reverse().join("");
    else
        return prestr + t.split("").reverse().join("") + "." + r;
}

/* 还原格式化金额 */
function rmoney(s) {
    return parseFloat(s.replace(/[^\d\.-]/g, ""));
}

/* 根据指定日期计算与指定日期的天数 */
function diffDays(s1){
    s1 = s1.replace(/-/g, "/");
    s1 = new Date(s1);
    s2 = new Date();
    var days= s1.getTime() - s2.getTime();
    var times = parseInt(Math.abs(days / (1000 * 60 * 60 * 24)));
    return times;
}

/* 截取金额后两位 */
function  fmoneyStr(money) {
    if(money.toString().indexOf(".")>-1){
        var length= money.toString().split(".")[1].length;
        if(length>2){
            var length1=money.toString().split(".")[0].length+3;
            return parseFloat(money.toString().substr(0,length1));
        }else{
            return parseFloat(money);
        }
    }else{
        return parseFloat(money);
    }
}
function returnGo() {
    window.history.go(-1);  //返回上一页
}
function returnBack() {
    window.history.back();  //返回上一页
}
function returnLocaGo() {
    window.location.go(-1); //刷新上一页
}

/* 微信网页授权  OAuth2.0 */
function wxAccredit(){
    if($.getStorage("xm_uData")){
        //用户存在
        com_obj.userId = JSON.parse($.getStorage("xm_uData")).userId;
    }
    if(window.localStorage.getItem('hx_wx')){
        //校验token是否有效
        $.VerifyAccessToken();
    }else{
        var Request = new Object();
        Request = $.GetRequest();
        var code = Request["code"];
        if(code && code!=""){
            //alert("code获取成功");
            //通过code换取网页授权access_token
            $.GetAccessToken();
        }else{
            $.GetWXCode();
        }
    }
    //

}

var jsEnter = function () {
    this.init();
};
jsEnter.prototype.init = function(){
    if($.getPara("Ios")!="" || $.getPara("Android")!="" ||$.getPara("iOS")!="" || com_obj.pageNoHrefWX!=undefined||!$.isWX()){
        //app嵌套环境执行
        PageInit();
    }else{
        //window.location.href ="/user/wx.html";
        PageInit();
    }
};
/* public入口 */
var com_obj={};
$(function () {
    var $init;
    if($.getStorage('xm_uData')){
        if(JSON.parse($.getStorage('xm_uData')).userId){
            com_obj.userId=JSON.parse($.getStorage('xm_uData')).userId;
        }else{
            com_obj.userId=0;
        }

        $init = new  jsEnter();
    }else{
        com_obj.userId=0;
        $init = new  jsEnter();
    }
    //if($.isWX()){
    //    if($.getStorage('xm_uData')&& $.getStorage('xmOpenid')){
    //
    //        $.updataInfo($.getStorage('xmOpenid'));
    //        com_obj.userId = JSON.parse($.getStorage('xm_uData')).userId;
    //        $init = new  jsEnter();
    //    }else{
    //        com_obj.userId=0;
    //        $init = new  jsEnter();
    //    }
    //}else{
    //    com_obj.userId=0;
    //    $init = new  jsEnter();
    //}


});
